package com.wonders.common.config.manager.instance;

import com.wonders.framework.config.manager.BaseManager;
import com.wonders.module.base.entity.vo.DicVo;
import com.wonders.module.base.service.DicService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 数据字典管理器
 * 
 * @author WuBin
 * 
 */
@Component
public class DicManager implements BaseManager {

	private Logger logger = LoggerFactory.getLogger(DicManager.class);

	/**
	 * 字典刷新间隔
	 */
	@Value("${dic.refrshTime}")
	private long refrshTime = 10;

	@Autowired
	private DicService dicService;

	/**
	 * 缓存字典值
	 */
	private Map<String, List<DicVo>> dicMap;

	/**
	 * 数据字典刷新线程
	 */
	private Thread thread;

	/**
	 * 数据字典刷新线程运行状态
	 */
	private volatile boolean runing = true;

	public void destroy() {
		runing = false;
		thread.interrupt();
	}

	public void init() {
		thread = new Thread(new Runnable() {
			public void run() {
				try {
					while (runing) {
						try {
							dicMap = dicService.getDicMap();
						} catch (Exception e) {
							logger.error("获取字典值出现异常", e);
						}
						Thread.sleep(refrshTime * 60L * 1000L);
					}
				} catch (InterruptedException e) {

				}
			}
		});
		thread.start();
	}

	/**
	 * 获取字典数据
	 * 
	 * @param dicType
	 *            字典类型
	 * @return 字典数据
	 */
	public List<DicVo> getDicList(String dicType) {
		return getDicList(dicType, null);
	}

	/**
	 * 获取字典数据
	 * 
	 * @param dicType
	 *            字典类型
	 * @param parentCode
	 *            父节点代码
	 * @return 字典数据
	 */
	public List<DicVo> getDicList(String dicType, String parentCode) {
		List<DicVo> dicList = (List<DicVo>) dicMap.get(dicType);
		if (dicList == null) {
			return null;
		}
		if (StringUtils.isEmpty(parentCode)) {
			return dicList;
		}
		List childDicList = new ArrayList();
		for (DicVo dic : dicList) {
			if (parentCode.equals(dic.getParentCode())) {
				childDicList.add(dic);
			}
		}
		return childDicList;
	}
}